const http = require('http')
require("libjv");


let isJsonStyle = (type, txt) => {
    if (!txt) {
        return false;
    }

    if (type == "object") {
        return true;
    }
    if (type != "string") {
        return false;
    }

    var len = txt.length;
    if (!len) {
        return false;
    }
    return (txt[0] == "{" && txt[len - 1] == "}") || (txt[0] == "[" && txt[len - 1] == "]")
}

let net = (method, url, postBody, headers) => {
    return new Promise((resolve, reject) => {

        if (!("Connection" in headers)) {
            headers["Connection"] = "keep-alive"
        }

        var postText = "";
        if (postBody) {
            var type = postBody.getJsType();
            if (type == "object") {
                postText = JSON.stringify(postBody);
            } else {
                postText = postBody;
            }
            if (isJsonStyle(type, postBody)
                && !("Content-Type" in headers)) {
                headers["Content-Type"] = 'application/json';
            }
            // headers["Content-Length"] = Buffer.byteLength(postBody);
        }


        let opt = {
            method: method,
            timeout: 2000,
            headers: headers || {}
        };

        var req = http.request(url, opt, res => {

            let list = [];
            res.on('data', chunk => {
                list.push(chunk);
            });
            res.on('end', () => {
                const text = Buffer.concat(list).toString();


                var response = {
                    body: text,
                    headers: res.headers || {},
                    status: res.statusCode,
                    contentType: res.headers["content-type"] || ""
                };

                let msgs = [];
                msgs.push(res.statusCode + " " + method + " " + url)
                msgs.push(opt.headers.toLogJsonText())
                if (postText) {
                    msgs.push(postText)
                }
                msgs.push(response.headers.toLogJsonText())
                msgs.push(text)

                logger.info(msgs.join("\n"));


                if (text && response.contentType.includes("json")) {
                    try {
                        response.json = JSON.parse(text);
                    } catch (e) {
                        logger.error("Json转换出错! " + text)
                    }
                }

                if (response.status.Between(200, 399)) {
                    resolve(response);
                } else {
                    reject(response);
                }
            });

        }).on('error', err => {
            logger.error(method + " " + url + " " + postText)
            reject(err);
        });

        if (postText) {
            req.write(postText);
        }
        req.end();
    });
}

let get = async (url) => {
    return await net("get", url);
}


let post = async (url, postBody) => {
    return await net("post", url, postBody);
}


module.exports.net = net;
module.exports.get = get;
module.exports.post = post;